#include "lib.h"
#include "libterm.c"
#include "libbox.c"
#include "libreadkeys.c"

void InitBoard(struct board *gboard) {
	rk_mytermsave();
	bzero(gboard, sizeof(struct board));
	return;
}

void PrintBoard(struct board gboard) {
	int i, j;
	
	for (i = 0; i < FIELDSIZE; i++) {
		for (j = 0; j < FIELDSIZE; j++) {
			bc_box(j * CELLSIZEX + j + 1 , i * CELLSIZEY + i + 1, CELLSIZEX, CELLSIZEY);
		}
	}
	
	for (i = 0; i < FIELDSIZE; i++) {
		for (j = 0; j < FIELDSIZE; j++) {
			switch (gboard.cell[i][j]) {
			case CROSS:
				mt_gotoXY(i * (CELLSIZEX + 1)  + SXDIV2, j * (CELLSIZEY + 1)  + SYDIV2);
				printf("X\n");
			break;
			case CRISS:
				mt_gotoXY(i * (CELLSIZEX + 1)  + SXDIV2, j * (CELLSIZEY + 1)  + SYDIV2);
				printf("0\n");
			break;
			case NONE:
			break;
			default:
				printf("O_o\n");
				return;
			break;
			}
		}
	}
	return;
}

int IsEnd(void) {
	int i, j;
	int result;
	int win1 = 0;
	int win2 = 0;
		
	for (i = 0; i < FIELDSIZE; i++) {
		result = 1;
		for (j = 0; j < FIELDSIZE; j++) {
			result *= gboard.cell[i][j];
		}
		if (result == 1) {
			win1++;
			break;
		}
		if (result == 8) {
			win2++;
			break;
		}
	}
	
	for (j = 0; j < FIELDSIZE; j++) {
		result = 1;
		for (i = 0; i < FIELDSIZE; i++) {
			result *= gboard.cell[i][j];
		}
		if (result == 1) {
			win1++;
			break;
		}
		if (result == 8) {
			win2++;
			break;
		}
	}
	
	result = 1;
	for (i = 0; i < FIELDSIZE; i++) {
		result *= gboard.cell[i][i];
	}
	if (result == 1) {
		win1++;
	}
	if (result == 8) {
		win2++;
	}

	result = 1;
	for (i = 0; i < FIELDSIZE; i++) {
		result *= gboard.cell[i][FIELDSIZE - i - 1];
	}
	if (result == 1) {
		win1++;
	}
	if (result == 8) {
		win2++;
	}

	if (win1) {
		return 1;
	} else if (win2) {
		return 2;
	} else {
		return 0;
	}
}
